package com.yqya.schedule.task.config;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import com.yqya.schedule.task.mapper.SysCronMapper;

/**
 * Schedule配置
 *
 * @author Kevin
 * @date 2019-07-14
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Autowired
    @SuppressWarnings("all")
    private SysCronMapper sysCronMapper;

    /**
     * 执行定时任务
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                // 1.添加任务内容（Runnable）
                () -> System.out.println("++++++ 执行定时任务：" + LocalDateTime.now().toLocalTime()),
                // 2.设置执行周期（Trigger）
                triggerContext -> {
                    // 2.1从数据库中获取执行周期
                    String cron = sysCronMapper.findFirstCron();
                    // 2.2合法性校验
                    if (StringUtils.isEmpty(cron)) {
                        System.out.println("++++++ 执行定时任务，获取的执行周期不合法。");
                    }
                    // 2.3返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
